package com.woniuxy.ticketcinema.exception.serviceException;

import com.woniuxy.ticketcinema.entity.ResponseResult;
import org.springframework.dao.DataAccessException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @ClassName TicketExceptionHandler
 * @Description TODO
 * @Author zx
 * @Date 2021-02-24 15:49:21
 * @Version 1.0
 */
@RestControllerAdvice
public class TicketExceptionHandler {
    @ExceptionHandler(NameExsitException.class)
    public ResponseResult<Void> exceptionHandler() {
        return new ResponseResult(101, "名称重复");
    }

    @ExceptionHandler(DataAccessException.class)
    public ResponseResult<Void> daExceptionHandler(DataAccessException e) {
        e.printStackTrace();
        return new ResponseResult(500, "fail");
    }


    @ExceptionHandler(DataException.class)
    public ResponseResult<Void> DataExceptionExceptionHandler(DataException e) {
        e.printStackTrace();
        return new ResponseResult(500, "数据有误");
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResponseResult<Object> MethodArgumentNotValidException(MethodArgumentNotValidException e) {
        System.out.println("---------------------------------------");
        BindingResult result = e.getBindingResult();
        if (result.hasErrors()) {
//            result.getAllErrors().forEach(c->System.out.println(c.getDefaultMessage()));
            HashMap<String, String> map = new HashMap();
            result.getFieldErrors().forEach(c -> map.put(c.getField(), c.getDefaultMessage()));
            ResponseResult<Object> responseResult = new ResponseResult();
            responseResult.setCode(102);
            responseResult.setMsg("无效参数");
            responseResult.setData(map);
            return responseResult;
//        return new ResponseResult(500,"传入参数有误");
        }
        return null;
    }
}
